package com.springsecirtytest.activiti1.controller;

import com.springsecirtytest.activiti1.SecurityUtil;
import com.springsecirtytest.activiti1.pojo.UserInfoBean;
import com.springsecirtytest.activiti1.util.AjaxResponse;
import com.springsecirtytest.activiti1.util.GlobalConfig;
import org.activiti.api.model.shared.model.VariableInstance;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.cert.TrustAnchor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/processInstance")
public class ProcessInstanceController {
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private ProcessRuntime processRuntime;


    @GetMapping(value = "/getInstances")
    public AjaxResponse getInstances(@AuthenticationPrincipal UserInfoBean userInfoBean) {
        Page<ProcessInstance> processInstances =null;
        try {

            if (GlobalConfig.Test) {
                securityUtil.logInAs("bajie");
            }

            processInstances = processRuntime.processInstances(Pageable.of(0, 100));
            List<ProcessInstance> list = processInstances.getContent();
            list.sort((y, x) -> x.getStartDate().toString().compareTo(y.getStartDate().toString()));

            ArrayList<HashMap<String, Object>> listMaps = new ArrayList<>();

            for (ProcessInstance pi : list) {

                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("id", pi.getId());
                hashMap.put("name", pi.getName());
                hashMap.put("status", pi.getStatus());
                hashMap.put("processDefinitionId", pi.getProcessDefinitionId());
                hashMap.put("processDefinitionKey", pi.getProcessDefinitionKey());
                hashMap.put("startDate", pi.getStartDate());
                hashMap.put("processDefinitionVersion", pi.getProcessDefinitionVersion());

                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                        .processDefinitionId(pi.getProcessDefinitionId()).singleResult();
                hashMap.put("deploymentId", processDefinition.getDeploymentId());
                hashMap.put("resourceName", processDefinition.getResourceName());

                listMaps.add(hashMap);
            }

            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                    , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                    , listMaps);
         }catch (Exception e) {
        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                "失败", e.toString());
    }
    }

    //启动流程实例
    @GetMapping("/startProcess")
    public AjaxResponse startProcess(@RequestParam("processDefintionKey") String processDefintionKey
            , @RequestParam("instanceName") String instanceName) {
try {

        if (GlobalConfig.Test) {
            securityUtil.logInAs("bajie");
        } else {
            securityUtil.logInAs(SecurityContextHolder.getContext().getAuthentication().getName());
        }

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey(processDefintionKey)
                .withName(instanceName)
                .withBusinessKey("自定义businessKey")
                .build());

        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                , processInstance);
}catch (Exception e) {
    return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
            "失败", e.toString());
}
    }
    //挂起任务
    @GetMapping("/suspendInstance")
    public  AjaxResponse suspendInstance(@RequestParam("instanceId") String instanceId){
        try {

            if (GlobalConfig.Test) {
                securityUtil.logInAs("bajie");
            }

            ProcessInstance suspend = processRuntime.suspend(ProcessPayloadBuilder
                .suspend()
                .withProcessInstanceId(instanceId)
                .build());

        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                , suspend);

        }catch (Exception e) {
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                    "失败", e.toString());
        }
    }

    //恢复任务
    @GetMapping( "/resumeInstance")
    public AjaxResponse resumeInstance(@RequestParam("instanceID") String instanceID) {

        try {
            if (GlobalConfig.Test) {
                securityUtil.logInAs("bajie");
            }

            ProcessInstance resume = processRuntime.resume(ProcessPayloadBuilder
                        .resume()
                        .withProcessInstanceId(instanceID)
                        .build());

        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                , resume);
       }catch (Exception e) {
           return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                   "失败", e.toString());
       }
    }

    //删除
        @GetMapping(value = "/deleteInstance")
    public AjaxResponse deleteInstance(@RequestParam("instanceID") String instanceID) {
     try {
         if (GlobalConfig.Test) {
             securityUtil.logInAs("bajie");
         }

         ProcessInstance delete = processRuntime.delete(ProcessPayloadBuilder
                .delete()
                .withProcessInstanceId(instanceID)
                .build());

        return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                , delete);
     }catch (Exception e) {
         return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                 "失败", e.toString());
     }
     }
    @GetMapping(value = "/variables")
    public AjaxResponse variables(@RequestParam("instanceID") String instanceID) {

        try {

            if (GlobalConfig.Test) {
                securityUtil.logInAs("bajie");
            }
            List<VariableInstance> variables = processRuntime.variables(ProcessPayloadBuilder
                    .variables()
                    .withProcessInstanceId(instanceID)
                    .build());

            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.SUCCESS.getCode()
                    , GlobalConfig.ResponseCode.SUCCESS.getDesc()
                    , variables);
        } catch (Exception e) {
            return AjaxResponse.ajaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                    "失败", e.toString());
        }
    }
}